<template>
  <el-card class="showCreateTopic" v-show="isShow">
    <div slot="header" class="clearfix">
      <span>{{ isShowTipStatus == 0 ? "添加" : "修改" }}题目</span>
      <el-button
        style="float: left; padding: 3px 0"
        type="text"
        @click="
          isShowTipStatus == 0 ? isShowCreateTopic() : isShowUpdateTopic()
        "
        >取消</el-button
      >
      <el-button
        style="float: right; padding: 3px 0"
        type="text"
        @click="onSubmitTopic()"
        >{{ isShowTipStatus == 0 ? "添加" : "修改" }}</el-button
      >
    </div>
    <el-scrollbar class="scrollbarBox">
      <div class="box">
        <el-form ref="item" :model="item" label-width="80px">
          <el-form-item label="题目名称:">
            <el-input
              v-model="item.name"
              :disabled="isState"
              style="width: 340px; margin-right: 10px"
              placeholder="格式：(调研对象名称) 的评价"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否必填:">
            <el-radio-group v-model="item.required">
              <el-radio :label="0" :disabled="isState">是</el-radio>
              <el-radio :label="1" :disabled="isState">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="调研对象:" style="text-align: left">
            <el-tag
              v-for="userinfo in item.target"
              :key="userinfo.id"
              style="margin-right: 10px"
              >{{ userinfo.name }}</el-tag
            >
            <el-tag
              v-if="isShowTipStatus == 0"
              type="warning"
              style="margin-right: 10px; cursor: pointer"
              @click="isShowUpdateUserinfoFun"
              ><i class="el-icon-edit"></i> 编辑
            </el-tag>
          </el-form-item>
          <el-form-item label="评分选项:">
            <el-input
              :disabled="isState"
              v-for="(scoreItem, index) in item.optionName.split(',')"
              :key="index"
              v-model="optionName[index]"
              style="width: 100px; text-align: center; margin-right: 10px"
            ></el-input>
          </el-form-item>
          <el-form-item label="二级题目:">
            <div class="weightBox clearfix" v-if="tableData.length != 0">
              <el-table :data="tableData" style="width: 500px; float: left">
                <el-table-column prop="name" label="题目组：" width="350">
                </el-table-column>
                <el-table-column label="权重" width="100">
                  <template slot-scope="scope">
                    <el-input
                      size="mini"
                      placeholder="权重"
                      type="number"
                      v-model="scope.row.weight"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-tag
                type="warning"
                style="cursor: pointer; font-size: 12; float: left"
                v-show="isShowTipStatus != 0"
                @click="updateWeights()"
                ><i class="el-icon-edit"></i> 修改
              </el-tag>
            </div>
            <div
              class="secondaryBox"
              v-for="(child, index) in item.group"
              :key="index"
            >
              <el-input
                v-model="child.name"
                style="width: 290px; margin-right: 10px"
                placeholder="请输入标题"
                :disabled="isState"
                ><template slot="prepend">标题</template></el-input
              >
              <el-input
                v-show="!isState"
                v-if="isShowTipStatus == 0"
                v-model="child.weight"
                type="number"
                style="width: 140px; margin-right: 10px"
                ><template slot="prepend">权重</template></el-input
              >
              <el-button
                :disabled="isState"
                v-show="!isShowTipStatus == 0"
                @click="updateSecondary(child.id)"
                >修改</el-button
              >
              <el-button
                style="color: red"
                @click="
                  isShowTipStatus == 0
                    ? deleteSecondary(index)
                    : deleteUpdateSecondary(child.id)
                "
                :disabled="isState"
                >删除</el-button
              >
            </div>
            <el-button
              @click="
                isShowTipStatus == 0 ? addSecondary() : showAddSmallProblem()
              "
              :disabled="isState"
              >添加标题</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>

    <UpdateUserinfo
      ref="child"
      @isShowUpdateUserinfo="isShowUpdateUserinfo"
      @onSubmitUserinfos="onSubmitUserinfos"
      :isShow="isShowUpdateUserinfos"
    />
    <el-dialog
      title="添加小问题"
      :visible.sync="dialogVisible"
      width="650px"
      :before-close="handleClose"
      :modal="false"
      top="30vh"
    >
      <el-input
        v-model="newGroup.name"
        style="width: 290px; margin-right: 10px"
        placeholder="请输入标题"
        :disabled="isState"
        ><template slot="prepend">标题</template></el-input
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSbumitSecondary()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import UpdateUserinfo from "./UpdateUserinfo.vue";
import { $http } from "../../request/service";
export default {
  name: "",
  props: ["isShow"],
  components: {
    UpdateUserinfo,
  },
  data() {
    return {
      optionName: ["优秀", "称职基本", "称职", "不称职"],
      isState: false, //修改添加 true已发布 false未发布
      isShowTipStatus: 0, //0添加，1修改
      item: {
        name: "",
        required: 0,
        weight: 0,
        optionName: "优秀,称职基本,称职,不称职",
        target: [],
        group: [
          {
            name: "",
            weight: 0,
          },
        ],
      },
      id: 0, //修改的索引
      isShowUpdateUserinfos: false, //是否显示人员修改列表
      newGroup: { name: "", weight: 0 },
      tableData: [],
      dialogVisible: false, //"添加小问题弹框的显示"
    };
  },
  methods: {
    //添加题目
    onSubmitTopic() {
      if (!this.item.name) {
        this.$message.warning("请先填写题目名称！");
        return;
      } else if (this.item.target.length == 0) {
        this.$message.warning("调研对象不能为空！");
        return;
      } else if (this.item.group.length == 0) {
        this.$message.warning("二级题目不能为空！");
        return;
      } else {
        let number = 0;
        this.item.group.forEach((item) => {
          if (!item.name) {
            this.$message.warning("请先填写二级题目名称！");
            return;
          }
          number += parseInt(item.weight);
        });
        if (number != 100) {
          this.$message.warning("二级题目权重总和必须是100！");
          return;
        }
      }
      let data = {};
      if (this.isShowTipStatus == 0) {
        data = this.item;
        data.optionName = this.optionName.join(",");
        let targetArray = [];
        console.log(this.item.target);
        this.item.target.forEach((items) => {
          targetArray.push(items.id);
        });
        data.target = targetArray;
        data.surveyId = 1;
        $http.post(`/survey/group/${this.id}`, data).then((res) => {
          if (res.code !== 200) return this.$message.error(res.message);
          this.$message.success("问题组添加成功！");
        });
      } else {
        let number = 0;
        this.item.group.forEach((item) => {
          number += parseInt(item.weight);
        });
        if (number != 100) {
          this.$message.warning("所有题目权重总和必须是100！");
          return;
        }
        data = {
          name: this.item.name,
          optionName: this.optionName.join(","),
          required: this.item.required,
          surveyId: this.item.surveyId,
          weight: this.item.weight,
        };
        $http.put(`/survey/group/${this.id}`, data).then((res) => {
          if (res.code !== 200) return this.$message.error(res.message);
          this.$message.success("问卷修改成功！");
        });
      }
      this.isShowCreateTopic();
    },
    isShowUpdateTopic() {
      let number = 0;
      this.item.group.forEach((item) => {
        number += parseInt(item.weight);
      });
      if (number != 100) {
        this.$message.warning("所有题目权重总和必须是100！");
        return;
      }
       this.isShowCreateTopic();
    },
    //修改题目获取旧数据
    updateChangeTip(id, value, isState) {
      this.isState = isState;
      this.isShowTipStatus = 1;
      this.item = value;
      this.optionName = value.optionName.split(",");
      this.id = id;
      let groupList = [];
      value.group.forEach((item) => {
        groupList.push({
          name: item.name,
          weight: item.weight,
          id: item.id,
          surveyId: id,
        });
      });
      this.tableData = groupList;
    },
    //添加题目获取状态
    addChangeTip(isState, id) {
      this.isState = isState;
      this.id = id;
      this.isShowTipStatus = 0;
    },
    //获取人员列表
    onSubmitUserinfos(value) {
      this.item.target = value;
    },
    //显示人员列表
    isShowUpdateUserinfoFun() {
      this.isShowUpdateUserinfos = true;
      this.$refs.child.getUserinfoList();
    },
    //关闭创建题库
    isShowCreateTopic() {
      this.$emit("changeData");
      this.isShowTipStatus = 0;
      this.optionName = ["优秀", "称职基本", "称职", "不称职"];
      this.item = {
        name: "",
        required: 0,
        weight: 0,
        optionName: "优秀,称职基本,称职,不称职",
        target: [],
        group: [
          {
            name: "",
            weight: 0,
          },
        ],
      };
      this.tableData = [];
    },
    //添加二级题目
    addSecondary() {
      this.item.group.push({ name: "", weight: 0 });
    },
    //显示小问题弹框
    showAddSmallProblem() {
      this.dialogVisible = true;
    },
    //小问题弹框回调
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    //提交小问题
    addSbumitSecondary() {
      if (!this.newGroup.name) {
        this.$message.warning("请先填写题目名称！");
        return;
      }
      let data = {
        groupId: this.id,
        name: this.newGroup.name,
        weight: this.newGroup.weight,
      };
      $http.post(`/survey/question`, data).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.$message.success("问题添加成功！");
        this.selectGroup();
      });
      this.dialogVisible = false;
      this.newGroup = {
        name: "",
        weight: 0,
      };
    },
    //删除二级题目
    deleteSecondary(index) {
      this.item.group.splice(index, 1);
    },
    //删除二级题目请求
    deleteopen(id) {
      this.$confirm(
        "此操作将永久删除该问题且该题目组的问题权重将归0, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          $http.delete(`/survey/question/${id}`).then((res) => {
            if (res.code !== 200) return this.$message.error(res.message);
            this.$message.success("问题删除成功！");
            this.selectGroup();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //修改二级题目
    updateSecondary(id) {
      let data = {
        groupId: this.item.id,
        name: "",
        weight: 0,
      };
      this.item.group.filter((item) => {
        if (item.id == id) {
          data.name = item.name;
        }
      });
      $http.put(`/survey/question/${id}`, data).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.$message.success("问题修改成功！");
      });
    },
    //批量修改权重
    updateWeights() {
      let number = 0;
      this.tableData.forEach((item) => {
        number += parseInt(item.weight);
      });
      if (number != 100) {
        this.$message.warning("所有题目权重总和必须是100！");
        return;
      }
      let data = {
        questionList: [],
      };
      this.tableData.forEach((item) => {
        data.questionList.push({
          id: parseInt(item.id),
          groupId: parseInt(this.item.id),
          weight: parseInt(item.weight),
        });
      });
      $http.put(`/survey/question/`, data).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.$message.success("问题组权重设置成功！");
        this.selectGroup();
        this.isShowCreateTopic();
      });
    },
    //删除修改二级题目
    deleteUpdateSecondary(id) {
      this.deleteopen(id);
    },
    //查询问题组
    selectGroup() {
      $http.get(`/survey/group/${this.item.id}`).then((res) => {
        if (res.code !== 200) return this.$message.error(res.message);
        this.item = res.data;
        let groupList = [];
        res.data.group.forEach((item) => {
          groupList.push({
            name: item.name,
            weight: item.weight,
            id: item.id,
            surveyId: res.data.id,
          });
        });
        this.tableData = groupList;
      });
    },
    //是否显示人员修改列表
    isShowUpdateUserinfo() {
      this.isShowUpdateUserinfos = false;
    },
  },
};
</script>

<style scoped>
.showCreateTopic {
  width: 50vw !important;
  min-width: 700px !important;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  z-index: 99;
}
.scrollbarBox {
  height: calc(90vh - 80px);
}
.showCreateTopic .box {
  text-align: left;
}
.secondaryBox {
  margin-bottom: 10px;
}
.weightBox {
  padding: 0px 0 20px;
  height: 100%;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>
